<template>
  <a-card size="small" :bordered="false" :hoverable="true">
    <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
      <a-tab-pane key="heartbeat" tab="心跳历史">
        <a-form class="smart-query-form" layout="inline">
          <a-form-item label="道路编号">
            <a-input v-model:value="heartbeatQuery.deviceRoad" style="width: 200px" readonly />
          </a-form-item>
          <a-form-item label="设备编号">
            <a-input-number v-model:value="heartbeatQuery.deviceId" :min="1" style="width: 160px" :disabled="true" />
          </a-form-item>
          <a-form-item label="心跳时间">
            <a-range-picker v-model:value="heartbeatDateRange" :presets="defaultChooseTimeRange" style="width: 280px" @change="handleHeartbeatDateChange" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="onHeartbeatSearch" :loading="heartbeatLoading">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button @click="resetHeartbeat" :disabled="heartbeatLoading">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-form-item>
        </a-form>

        <a-table
          size="small"
          bordered
          class="smart-margin-top16"
          :loading="heartbeatLoading"
          :dataSource="heartbeatTableData"
          :columns="heartbeatColumns"
          rowKey="requestId"
          :pagination="false"
        />
        <div class="smart-query-table-page">
          <a-pagination
            showSizeChanger
            showQuickJumper
            show-less-items
            :pageSizeOptions="PAGE_SIZE_OPTIONS"
            v-model:current="heartbeatQuery.pageNum"
            v-model:pageSize="heartbeatQuery.pageSize"
            :total="heartbeatTotal"
            :disabled="heartbeatLoading"
            @change="fetchHeartbeat"
            @showSizeChange="fetchHeartbeat"
            :show-total="(total) => `共${total}条`"
          />
        </div>
      </a-tab-pane>

      <a-tab-pane key="response" tab="响应历史">
        <a-form class="smart-query-form" layout="inline">
          <a-form-item label="道路编号">
            <a-input v-model:value="responseQuery.deviceRoad" style="width: 200px" readonly />
          </a-form-item>
          <a-form-item label="设备编号">
            <a-input-number v-model:value="responseQuery.deviceId" :min="1" style="width: 160px" :disabled="true" />
          </a-form-item>
          <a-form-item label="请求ID">
            <a-input v-model:value="responseQuery.requestId" placeholder="请输入请求ID" allowClear style="width: 240px" />
          </a-form-item>
          <a-form-item label="状态">
            <a-select v-model:value="responseQuery.status" :options="statusOptions" allowClear style="width: 160px" placeholder="请选择状态" />
          </a-form-item>
          <a-form-item label="响应时间">
            <a-range-picker v-model:value="responseDateRange" :presets="defaultChooseTimeRange" style="width: 280px" @change="handleResponseDateChange" />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="onResponseSearch" :loading="responseLoading">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
          </a-form-item>
          <a-form-item>
            <a-button @click="resetResponse" :disabled="responseLoading">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-form-item>
        </a-form>

        <a-table
          size="small"
          bordered
          class="smart-margin-top16"
          :loading="responseLoading"
          :dataSource="responseTableData"
          :columns="responseColumns"
          rowKey="requestId"
          :pagination="false"
        />
        <div class="smart-query-table-page">
          <a-pagination
            showSizeChanger
            showQuickJumper
            show-less-items
            :pageSizeOptions="PAGE_SIZE_OPTIONS"
            v-model:current="responseQuery.pageNum"
            v-model:pageSize="responseQuery.pageSize"
            :total="responseTotal"
            :disabled="responseLoading"
            @change="fetchResponse"
            @showSizeChange="fetchResponse"
            :show-total="(total) => `共${total}条`"
          />
        </div>
      </a-tab-pane>
    </a-tabs>
  </a-card>
</template>

<script setup>
  import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue';
  import { Tag } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { h, onMounted, reactive, ref } from 'vue';
  import { trafficControlApi } from '/@/api/support/traffic-control-api';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { MQTT_STATUS_COLOR_MAP, MQTT_STATUS_LABEL_MAP, MQTT_STATUS_OPTIONS, HEARTBEAT_HISTORY_QUERY_DEFAULT } from '/@/constants/support/traffic-const';
  import { defaultTimeRanges } from '/@/lib/default-time-ranges';
  import { smartSentry } from '/@/lib/smart-sentry';

  const activeTab = ref('heartbeat');

  const heartbeatDateRange = ref([]);
  const responseDateRange = ref([]);

  const statusOptions = MQTT_STATUS_OPTIONS;
  const defaultChooseTimeRange = defaultTimeRanges;

  const DEFAULT_DEVICE_ROAD = '1201100';
  const DEFAULT_DEVICE_ID = 2;

  const heartbeatQuery = reactive({ ...HEARTBEAT_HISTORY_QUERY_DEFAULT, deviceRoad: DEFAULT_DEVICE_ROAD, deviceId: DEFAULT_DEVICE_ID });
  const responseQuery = reactive({ ...HEARTBEAT_HISTORY_QUERY_DEFAULT, deviceRoad: DEFAULT_DEVICE_ROAD, deviceId: DEFAULT_DEVICE_ID });

  const heartbeatLoading = ref(false);
  const responseLoading = ref(false);

  const heartbeatTableData = ref([]);
  const responseTableData = ref([]);
  const heartbeatTotal = ref(0);
  const responseTotal = ref(0);

  const responseLoaded = ref(false);

  const heartbeatColumns = [
    { title: '请求ID', dataIndex: 'requestId', ellipsis: true },
    { title: '当前模式', dataIndex: 'currentMode', width: 160 },
    { title: '心跳间隔 (秒)', dataIndex: 'interval', width: 160 },
    {
      title: '心跳时间',
      dataIndex: 'timestamp',
      width: 200,
      customRender: ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },
  ];

  const responseColumns = [
    { title: '请求ID', dataIndex: 'requestId', ellipsis: true },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      customRender: ({ text }) => {
        if (!text) {
          return '-';
        }
        const color = MQTT_STATUS_COLOR_MAP[text] || 'default';
        const label = MQTT_STATUS_LABEL_MAP[text] || text;
        return h(Tag, { color }, () => label);
      },
    },
    { title: '消息', dataIndex: 'message', width: 220, ellipsis: true },
    { title: '当前模式', dataIndex: 'currentMode', width: 160 },
    { title: '心跳间隔 (秒)', dataIndex: 'interval', width: 160 },
    { title: '闪烁时长 (秒)', dataIndex: 'flashtime', width: 160 },
    {
      title: '响应时间',
      dataIndex: 'timestamp',
      width: 200,
      customRender: ({ text }) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-'),
    },
  ];

  function handleHeartbeatDateChange(_, dateStrings) {
    heartbeatQuery.startTime = dateStrings?.[0] || undefined;
    heartbeatQuery.endTime = dateStrings?.[1] || undefined;
  }

  function handleResponseDateChange(_, dateStrings) {
    responseQuery.startTime = dateStrings?.[0] || undefined;
    responseQuery.endTime = dateStrings?.[1] || undefined;
  }

  async function fetchHeartbeat() {
    try {
      heartbeatLoading.value = true;
      const responseModel = await trafficControlApi.queryHeartbeatHistory({ ...heartbeatQuery });
      heartbeatTableData.value = responseModel?.data?.list || [];
      heartbeatTotal.value = responseModel?.data?.total || 0;
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      heartbeatLoading.value = false;
    }
  }

  async function fetchResponse() {
    try {
      responseLoading.value = true;
      const responseModel = await trafficControlApi.queryResponseHistory({ ...responseQuery });
      responseTableData.value = responseModel?.data?.list || [];
      responseTotal.value = responseModel?.data?.total || 0;
    } catch (error) {
      smartSentry.captureError(error);
    } finally {
      responseLoading.value = false;
    }
  }

  function onHeartbeatSearch() {
    heartbeatQuery.pageNum = 1;
    fetchHeartbeat();
  }

  function onResponseSearch() {
    responseQuery.pageNum = 1;
    fetchResponse();
  }

  function resetHeartbeat() {
    Object.assign(heartbeatQuery, { ...HEARTBEAT_HISTORY_QUERY_DEFAULT, deviceRoad: DEFAULT_DEVICE_ROAD, deviceId: DEFAULT_DEVICE_ID });
    heartbeatDateRange.value = [];
    fetchHeartbeat();
  }

  function resetResponse() {
    Object.assign(responseQuery, { ...HEARTBEAT_HISTORY_QUERY_DEFAULT, deviceRoad: DEFAULT_DEVICE_ROAD, deviceId: DEFAULT_DEVICE_ID });
    responseDateRange.value = [];
    fetchResponse();
  }

  function handleTabChange(key) {
    if (key === 'response' && !responseLoaded.value) {
      fetchResponse();
      responseLoaded.value = true;
    }
  }

  onMounted(() => {
    fetchHeartbeat();
  });
</script>

